package cn.topcodes.tcsf.app.web.controller.admin;

import cn.topcode.unicorn.utils.RenderUtil;
import cn.topcode.unicorn.utils.UuidUtil;
import cn.topcodes.tcsf.admin.commons.api.controller.admin.AdminController;
import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.admin.commons.api.security.ShiroUtil;
import cn.topcodes.tcsf.admin.commons.domain.Page;
import cn.topcodes.tcsf.app.domain.api.Notices;
import cn.topcodes.tcsf.app.domain.api.imageContentUploadVo;
import cn.topcodes.tcsf.app.domain.entity.Notice;
import cn.topcodes.tcsf.app.domain.form.NoticeForm;
import cn.topcodes.tcsf.app.service.NoticeService;
import cn.topcodes.tcsf.app.service.impl.ConfigService;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author Unicorn
 * @date 2017/5/5
 */
@Controller
@RequestMapping("/admin/notice")
public class NoticeAdminController extends AdminController<Notice, Notices, NoticeForm> {

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private ConfigService configService;

    @Override
    protected String getPageFolder() {
        return "app/admin/notice";
    }

    @RequestMapping("insertNotice")
    @ResponseBody
    public ApiResponseEntity insertNotice(HttpServletRequest request,
                                          @Valid NoticeForm noticeForm,
                                          BindingResult result) {

        noticeService.insertNotice(noticeForm, ShiroUtil.getUserId());
        return ApiResponseEntity.buildOK();
    }

    /**
     * 上传图片
     *
     * @param img
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "uploderContentImage")
    public void uploaderContentImage(@RequestParam(required = true, value = "img") MultipartFile[] img,
                                     HttpServletResponse response) throws IOException {
        String basePath = configService.getFileFolderPath();
        List<String> contentPaths = new ArrayList<>();
        imageContentUploadVo imageUploderVo = new imageContentUploadVo();
        for (MultipartFile multipartFile : img) {
            String imgPath = "content-img/" + UuidUtil.getUUID() + "." + multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new File(basePath + imgPath));
            contentPaths.add(OtherController.FILE_PATH + "?path=" + imgPath);
        }
        imageUploderVo.setErrno(0);
        imageUploderVo.setData(contentPaths);
        RenderUtil.renderJson(imageUploderVo, response);
    }

    @Override
    public ApiResponseEntity<Page<Notices>> pageList(HttpServletRequest request,
                                                     @ApiParam("页号") @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageNumber,
                                                     @ApiParam("每页条数") @RequestParam(value = "size", required = false, defaultValue = "10") Integer pageSize) {
        Map<String, String[]> searchParams = request.getParameterMap();
        Page<Notice> pageT = this.noticeService.findPage(searchParams, pageNumber.intValue(), pageSize.intValue());
        Page<Notices> pageV = this.entity2Vo(pageT, request);
        ApiResponseEntity<Page<Notices>> apiResponse = ApiResponseEntity.buildOK();
        return apiResponse.setBody(pageV);
    }

    @Override
    protected void entity2VoDiff(Notice entity, Notices vo) {
        String content = entity.getContent();
        content = content.replaceAll("&gt;", ">");
        content = content.replaceAll("&lt;", "<");
        content = content.replaceAll("&quot;", "'");
        content = content.replaceAll("&amp;", "&");
        content = content.replaceAll("&nbsp;", " ");
        vo.setContent(content);
        vo.setDay(calculationDay(entity.getCreatedTime()));
        super.entity2VoDiff(entity, vo);
    }

    private String calculationDay(Date createdTime) {

        int days = differentDays(createdTime, new Date());
        if (days == 0) {
            return "今天";
        } else if (days == 1) {
            return "昨天";
        } else if (days == 2) {
            return "前天";
        } else if (days >= 7 && days < 30) {
            return "一个星期前";
        } else {
            return "一个月前";
        }
    }

    /**
     * date2比date1多的天数
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDays(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2) { //同一年
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {//闰年
                    timeDistance += 366;
                } else {//不是闰年
                    timeDistance += 365;
                }
            }

            return timeDistance + (day2 - day1);
        } else { //不同年
            return day2 - day1;
        }
    }
}
